package com.zha;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

//wordcount  spark  java版

/**
 * 这个程序和下一个程序一样，只是注释多少的问题
 */



public class WORD {
    public static void main(String[] args) {
        //配置spark
        SparkConf conf = new SparkConf().setAppName("WORD").setMaster("local");
        //创建连接
        JavaSparkContext jps = new JavaSparkContext(conf);
        //获取文件路径
        JavaRDD<String> line = jps.textFile("f://a.txt");
        //flatMap算子  切分原文件   new FlatMapFunction
        JavaRDD<String> words  = line.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                String[] split = s.split(",");
                return Arrays.asList(split).iterator();
            }
        });
        //mapToPair算子   给每个元素标记   new PairFunction
        // 这里的结果是2部分，一个元素，一个数字，所以用scala的元组 Tuple来放
        JavaPairRDD<String, Integer> map = words.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s,1);
            }
        });
         //reduceByKey      根据元素来计算元素数量  new Function2
        JavaPairRDD<String, Integer> wordcount = map.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });


          //foreach  触发程序运行
          //输出的结果也是2部分，用Tuple元组 new VoidFunction
        wordcount.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            @Override
            public void call(Tuple2<String, Integer> s ) throws Exception {
                System.out.println(s._1 +","+ s._2);
            }
        });
        //关闭资源
         jps.close();
    }
}
